package com.jcompressor.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.ObjectUtils;

/**
 * The Regex Utilities
 * @author Scott Carnett
 */
public class RegexUtils {
	
	public static final String TEMPLATE_ID_PHASE1 = "[^a-zA-Z0-9\\-_ ]";
	public static final String TEMPLATE_ID_PHASE2 = "[\\-_ ]";
	
	/**
	 * Invokes the regex pattern compiler
	 * @param pattern the pattern
	 * @return Pattern with the pattern
	 * @see com.fdlic.core.utils.RegexUtils#compile(String, int)
	 */
	public static Pattern compile(final String pattern) {
		return Pattern.compile(pattern);
	}
	
	/**
	 * Invokes the regex pattern compiler
	 * @param pattern the pattern
	 * @param flags the flags
	 * @return Pattern with the pattern
	 * @see com.fdlic.core.utils.RegexUtils#compile(String)
	 */
	public static Pattern compile(final String pattern, final int flags) {
		return Pattern.compile(pattern, flags);
	}
	
	/**
	 * Gets the pattern matcher
	 * @param pattern the pattern
	 * @param str the string
	 * @return Matcher with the pattern matcher
	 */
	public static Matcher match(final String pattern, final String str) {
		final Matcher matcher = RegexUtils.compile(pattern).matcher(str);
		return matcher;
	}
	
	/**
	 * Checks for a pattern matche in a string
	 * @param pattern the pattern
	 * @param obj the object
	 * @return boolean with the value of true if the pattern matches; otherwise false
	 * @see com.fdlic.core.utils.RegexUtils#matches(String, String)
	 */
	public static boolean matches(final String pattern, final Object obj) {
		return RegexUtils.matches(pattern, ObjectUtils.toString(obj));
	}
	
	/**
	 * Checks for a pattern matche in a string
	 * @param pattern the pattern
	 * @param str the string
	 * @return boolean with the value of true if the pattern matches; otherwise false
	 * @see com.fdlic.core.utils.RegexUtils#matches(String, Object)
	 */
	public static boolean matches(final String pattern, final String str) {
		final Matcher matcher = RegexUtils.match(pattern, str);
		if (matcher.matches()) {
			return true;
		}
		
		return false;
	}
	
	/**
	 * Finds a match
	 * @param pattern the pattern
	 * @param str the string
	 * @return boolean with the value of true if the pattern is found; otherwise false
	 */
	public static boolean find(final String pattern, final String str) {
		final Matcher matcher = RegexUtils.match(pattern, str);
		return matcher.find();
	}
	
	/**
	 * Replaces a pattern with the specified replacement
	 * @param str the string
	 * @param pattern the pattern
	 * @param replacement the replacement
	 * @return String with the new string
	 */
	public static String replaceAll(final String str, final String pattern, final String replacement) {
		final Matcher matcher = RegexUtils.match(pattern, str);
		return matcher.replaceAll(replacement);
	}
	
}